package com.zqyl.docmanager.controller;

import com.zqyl.docmanager.entity.UploadFile;
import com.zqyl.docmanager.service.DocumentConverterService;
import com.zqyl.docmanager.service.UploadFileService;
import com.zqyl.docmanager.vo.UploadFileVO;
import com.zqyl.docmanager.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
@CrossOrigin
public class UploadFileController {

    @Autowired
    private UploadFileService uploadFileService;

    @Autowired
    private DocumentConverterService documentConverterService;

    @GetMapping("/files")
    public ResponseEntity<Map<String, Object>> listFiles(
            @RequestParam(required = false) String format,
            @RequestParam(required = false) String fileName) {
        try {
            List<UploadFile> files = uploadFileService.searchFiles(format, fileName);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", files);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error listing files", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "Failed to list files: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            log.info("Receiving file upload request: {}", file.getOriginalFilename());
            
            UploadFile uploadedFile = uploadFileService.uploadFile(file);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "File uploaded successfully");
            response.put("fileId", uploadedFile.getId());
            response.put("fileName", uploadedFile.getFileName());
            response.put("fileSize", uploadedFile.getFileSize());
            response.put("format", uploadedFile.getFormat());
            response.put("status", uploadedFile.getStatus());
            
            log.info("File uploaded successfully: {}", uploadedFile.getFileName());
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            log.error("Error uploading file", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "Failed to upload file: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/files/{id}")
    public ResponseEntity<Map<String, Object>> deleteFile(@PathVariable Long id) {
        try {
            uploadFileService.deleteFile(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "File deleted successfully");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error deleting file", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "Failed to delete file: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/files/{id}")
    public ResponseEntity<Map<String, Object>> getFile(@PathVariable Long id) {
        try {
            UploadFile file = uploadFileService.getFile(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", file);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error retrieving file", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "Failed to retrieve file: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/query")
    public ResponseEntity<List<UploadFileVO>> queryFiles(@RequestParam(required = false) String format,
                                                        @RequestParam(required = false) String fileName) {
        List<UploadFileVO> files = uploadFileService.queryFiles(format, fileName);
        return ResponseEntity.ok(files);
    }

    @GetMapping("/formats")
    public ResponseEntity<List<String>> getAllFormats() {
        List<String> formats = uploadFileService.getAllFormats();
        return ResponseEntity.ok(formats);
    }

    @PostMapping("/files/{id}/convert/markdown")
    public Result<Map<String, String>> convertToMarkdown(@PathVariable Long id) {
        try {
            UploadFile file = uploadFileService.getFileById(id);
            if (file == null) {
                return Result.error("文件不存在");
            }

            String content;
            byte[] fileContent = uploadFileService.getFileContent(file.getFilePath());

            switch (file.getFormat().toLowerCase()) {
                case "docx":
                case "doc":
                    content = documentConverterService.wordToMarkdown(fileContent);
                    break;
                case "pdf":
                    content = documentConverterService.pdfToMarkdown(fileContent);
                    break;
                default:
                    return Result.error("不支持的文件格式");
            }

            Map<String, String> response = new HashMap<>();
            response.put("content", content);
            return Result.success(response);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("转换失败：" + e.getMessage());
        }
    }
} 